package com.xinxi11.project.qx.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.tools.ant.taskdefs.Tstamp.Unit;

import com.xinxi11.module.core.web.struts2.CrudStruts2ActionSupport;
import com.xinxi11.module.core.web.struts2.Struts2Utils;
import com.xinxi11.project.qx.beans.QxRole;
import com.xinxi11.project.qx.services.IQxRoleService;

/**
 * 角色action处理
 * 
 * @author 吴培雷
 * @date 2011-8-22
 */
public class QxRoleAction extends CrudStruts2ActionSupport {

	private static final long serialVersionUID = -1253931857437710993L;
	private IQxRoleService qxRoleService;
	private String id;
	private String roleType;// 权限组类型

	public String getRoleType() {
		return roleType;
	}

	public void setRoleType(String roleType) {
		this.roleType = roleType;
	}

	

	public void setQxRoleService(IQxRoleService qxRoleService) {
		this.qxRoleService = qxRoleService;
	}

	public void setId(String id) {
		this.id = id;
	}

	

	@Override
	public String list() throws Exception {
		// 当前用户角色，不含子角色
		List<QxRole> directRoles = qxRoleService.findDirectRoles(getLoginUser()
				.getId());
		StringBuffer roleIds = new StringBuffer();
		if (CollectionUtils.isNotEmpty(directRoles)) {
			for (QxRole role : directRoles) {
				roleIds.append(role.getId());
				roleIds.append(",");
			}
		}
		Struts2Utils.getRequest().setAttribute("rootRoleIds",
				roleIds.toString());
		return LIST;
	}

	/** 查看角色权限 */
	public String look() throws Exception {
		// 角色信息
		dto = qxRoleService.findRoleById(getSid());
		// 查看角色下岗位信息
		listRoleDuty = qxRoleDutyService.findByRoleId(getSid());
		// 当前登录人id
		Long loginUserId = getLoginUser().getId();
		Struts2Utils.getRequest().setAttribute("loginUserId", loginUserId);
		return LOOK;
	}

	/** ajax删除角色 */
	@SuppressWarnings("unchecked")
	public void ajaxDelete() throws Exception {
		JSONObject obj = new JSONObject();
		// 查询该角色下所有角色
		List<QxRole> listRole = qxRoleService.findRolesByUserRole(id);
		if (listRole == null || listRole.size() == 0)
			throw new Exception("异常：删除角色，角色ids为空！");
		Collection ids = new ArrayList();
		for (QxRole role : listRole) {
			ids.add(role.getId());
		}
		boolean b = qxRoleService.deleteActive(ids, QxRole.class);
		obj.put("result", b);
		Struts2Utils.renderJson(obj);
	}

	/** 跳转到 添加页面 */
	public String tosave() throws Exception {
		String parentNodeId = id;
		if (StringUtils.isBlank(parentNodeId))
			throw new Exception("异常：添加子角色，父角色Id不能为空!");
		QxRole parentRole = qxRoleService.findRoleById(parentNodeId);
		if (parentRole != null) {
			HttpServletRequest req = Struts2Utils.getRequest();
			req.setAttribute("parentRoleId", parentNodeId);
			req.setAttribute("parentRoleName", parentRole.getName());
			req.setAttribute("parentUnitId", parentRole.getUnitId());
			req.setAttribute("parentUnitName", parentRole.getUnitName());
			// 判断是普通权限组还是管理员权限组
			roleType = parentRole.getType();
		}
		return super.tosave();
	}

	/** 跳转到修改页面 */
	public String toupdate() throws Exception {
		// 包含父类名称,部门名称等
		dto = qxRoleService.findRoleById(id);
		QxRole role = (QxRole) dto;
		// 判断是普通权限组还是管理员权限组
		roleType = role.getType();
		if (StringUtils.isNotBlank(role.getParentId())) {
			// 父角色
			QxRole parentRole = qxRoleService.findRoleById(role.getParentId());
			Struts2Utils.getRequest().setAttribute("parentRole", parentRole);
		}
		return UPDATE;
	}

	// ajax校验子角色是否在父角色部门下
	public void ajaxCheckRoleUnit() throws Exception {
		JSONObject obj = new JSONObject();
		boolean isUnitValid = checkRoleUnit();
		obj.put("result", isUnitValid);
		Struts2Utils.renderJson(obj);
	}

	// 检测角色名称是否已经存在
	public void ajaxCheckRoleExsit() throws Exception {
		JSONObject obj = new JSONObject();
		QxRole role = qxRoleService.findByName(queryString);
		String roleId = null;
		if (role != null && role.getId() != null) {
			roleId = role.getId();
		}
		obj.put("roleId", roleId);
		Struts2Utils.renderJson(obj);
	}

	public boolean checkRoleUnit() throws Exception {
		boolean b = false;
		Long unitId = NumberUtils.toLong(id);
		Long parentId = NumberUtils.toLong(sid);
		if (parentId == 0)
			return true;
		// 子角色部门id
		Unit unit = qxRoleService.findById(unitId, Unit.class);
		// 父角色部门id
		Unit parentUnit = qxRoleService.findById(parentId, Unit.class);
		// 比较两个部门的level
		if (unit.getUnitNumber().indexOf(parentUnit.getUnitNumber()) != -1) {
			b = true;
		}
		return b;
	}

	/** 添加 */
	public String save() throws Exception {
		QxRole role = (QxRole) dto;
		if (StringUtils.isBlank(role.getParentId()))
			return null;
		// 父角色
		QxRole parentRole = qxRoleService.findById(role.getParentId(),
				QxRole.class);
		// 子角色中ID最大的
		QxRole maxRole = qxRoleService.findMaxRole(role.getParentId());
		// 父角色level
		Integer parentLevel = (role.getParentId().length() - 1) / 3 + 1;
		// 父角色权限组
		String parentType = parentRole.getType();
		// 设置角色权限组
		role.setType(parentType);
		// 设置角色level
		role.setLevel(parentLevel + 1);
		// 设置角色id
		if (maxRole == null) {
			role.setId(role.getParentId() + "001");
		} else {
			role.setId(String.valueOf(Long.valueOf(maxRole.getId()) + 1));
		}
		// 设置创建人
		role.setCreatePerson(getLoginUser().getUserName());
		// 设置创建时间
		role.setCreateTime(DateUtils.formatDate(new Date()));
		return super.save();
	}

	/** 修改 */
	public String update() throws Exception {
		// 页面Dto
		QxRole rolePage = (QxRole) dto;
		if (StringUtils.isBlank(rolePage.getId()))
			throw new Exception("异常：角色修改,角色id不能为空！");
		// findById
		QxRole role = qxRoleService.findById(rolePage.getId(), QxRole.class);
		// 更新角色名称
		role.setName(rolePage.getName());
		// 更新生效时间
		role.setStartDate(rolePage.getStartDate());
		// 失效时间
		role.setEndDate(rolePage.getEndDate());
		// 部门范围
		role.setUnitId(rolePage.getUnitId());
		// 授权范围
		role.setIsLimit(rolePage.getIsLimit());
		// 更新人
		role.setUpdatePerson(getLoginUser().getUserName());
		// 更新时间
		role.setUpdateTime(DateUtils.formatDate(new Date()));
		qxRoleService.update(role);
		return LIST;
	}

	/** ajax获取相应角色的详细信息 */
	public void ajaxRoleInfo() throws Exception {
		String roleId = id;
		QxRole role = qxRoleService.findRoleById(roleId);
		if (role != null) {
			JSONObject obj = new JSONObject();
			obj.put("roleName", role.getName());
			obj.put("parentRoleName", role.getParentRoleName());
			obj.put("startDate", DateUtils.convertDate2String(role
					.getStartDate()));
			obj.put("endDate", DateUtils.convertDate2String(role.getEndDate()));
			obj.put("unitName", role.getUnitName());
			obj.put("createDate", DateUtils.convertDate2String(role
					.getCreateTime()));
			obj.put("createPerson", role.getCreatePerson());
			obj.put("updateDate", DateUtils.convertDate2String(role
					.getUpdateTime()));
			obj.put("updatePerson", role.getUpdatePerson());
			if (role.getIsLimit() != null) {
				if (2 == role.getIsLimit().intValue()) {
					obj.put("isLimit", "允许授权");
				} else {
					obj.put("isLimit", "不允许授权");
				}
			}
			Struts2Utils.renderJson(obj);
		}
	}

	/** 获取某角色下的所有子角色 */
	public void ajaxRoleTreeByRoleId() throws Exception {
		String roleId = id;
		List<QxRole> qxRoleList = qxRoleService.findRolesByUserRole(roleId);
		String[] ss = { roleId };
		List<QxRole> directRoles = qxRoleService.findRolesByIds(Arrays
				.asList(ss));
		Struts2Utils.renderJson(createRoleTree(directRoles, qxRoleList));
	}

	/** 获取当前用户的角色树 */
	public void ajaxRoleTree() throws Exception {
		Long userId = getLoginUser().getId();
		// 当前用户角色和子角色
		List<QxRole> qxRoleList = qxRoleService.findRoleByUser(userId);
		// 当前用户角色，不含子角色
		List<QxRole> directRoles = qxRoleService.findDirectRoles(userId);
		Struts2Utils.renderJson(createRoleTree(directRoles, qxRoleList));
	}

	/** 获取当前用户的角色树（去除已经失效的） */
	public void ajaxRoleTreeReal() throws Exception {
		Long userId = getLoginUser().getId();
		// 当前用户角色和子角色
		List<QxRole> qxRoleList = qxRoleService.findRoleByUser(userId);
		// 当前时间
		Date nowDate = DateUtils.formatDate(new Date());
		// 去除已经失效的角色 (如果失效日期为null为永久有效)
		if (CollectionUtils.isNotEmpty(qxRoleList)) {
			List<QxRole> qxRoleListReal = new ArrayList<QxRole>();
			for (QxRole role : qxRoleList) {
				Date endDate = role.getEndDate();
				if (endDate == null
						|| (DateUtils.compare_date(endDate, nowDate) >= 0)) {
					qxRoleListReal.add(role);
				}
			}
			qxRoleList = qxRoleListReal;
		}
		// 当前用户角色，不含子角色
		List<QxRole> directRoles = qxRoleService.findDirectRoles(userId);
		// 去除已经失效的直接角色
		if (CollectionUtils.isNotEmpty(directRoles)) {
			List<QxRole> directRolesReal = new ArrayList<QxRole>();
			for (QxRole role : directRoles) {
				Date endDate = role.getEndDate();
				if (endDate == null
						|| (DateUtils.compare_date(endDate, nowDate) >= 0)) {
					directRolesReal.add(role);
				}
			}
			directRoles = directRolesReal;
		}
		Struts2Utils.renderJson(createRoleTree(directRoles, qxRoleList));
	}

	/** 根据list创建角色树 */
	public String createRoleTree(List<QxRole> directRoles,
			List<QxRole> qxRoleList) {
		JSONArray json = roleChildTreeNode(directRoles, qxRoleList);
		return json.toString();
	}

	// 角色树子节点
	private JSONArray roleChildTreeNode(List<QxRole> childRoles,
			List<QxRole> qxRoleList) {
		JSONArray jsonArray = new JSONArray();
		if (childRoles != null && childRoles.size() > 0) {
			for (QxRole role : childRoles) {
				jsonArray.add(roleTreeNode(role, qxRoleList));
			}
		}
		return jsonArray;
	}

	// 角色树节点
	private JSONObject roleTreeNode(QxRole role, List<QxRole> qxRoleList) {
		JSONObject json = new JSONObject();
		json.put("data", role.getName());
		JSONObject attributes = new JSONObject();
		attributes.put("id", role.getId());
		attributes.put("name", role.getName());
		attributes.put("unitId", role.getUnitId());
		attributes.put("isLimit", role.getIsLimit());
		json.put("attr", attributes);
		// 查找改角色下面的直接子角色
		List<QxRole> childRoles = new ArrayList<QxRole>();
		for (QxRole qxRole : qxRoleList) {
			String roleId = qxRole.getId();
			if (((roleId.length() >= 3) && roleId.substring(0,
					roleId.length() - 3).equals(role.getId()))) {
				childRoles.add(qxRole);
			}
		}
		if (childRoles != null && childRoles.size() > 0) {
			json.put("children", roleChildTreeNode(childRoles, qxRoleList));
		}
		return json;

	}
}
